﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.Security;
using ETL.Business.Handlers.ProjectActualResourceHandler;
using ETL.Business.Handlers.ProjectHandlers;
using ETL.Business.Handlers.ProjectScheduledResourceUsageHandler;
using ETL.Business.Handlers.ProjectTaskHandler;
using ETL.Business.Handlers.ProjectUserHandler;
using ETL.Business.Helpers;
using ETL.Business.Models;
using ETL.Common;
using ETL.Common.Logging;
using ETL.Web.CustomCredential;
using ETL.Web.Models;
using WebMatrix.WebData;

namespace ETL.Web.Controllers
{
    [Authorize]
    public class ManageTaskController : Controller
    {
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public ActionResult Index()
        {
            // check authenticated
            if (!WebSecurity.IsAuthenticated) return RedirectToAction("Login", "Account");

            // Program Initialize
            (new ProgramInitialize()).Execute(ETLCredential.UserId, ETLCredential.UserFullName);

            // prepare date of viewmodel
            var etrTaskViewModel = new ManageTaskViewModel();

            #region Check user role for projects loading

            // Check roles of user
            if (Roles.IsUserInRole(Constants.RoleName.Admin))
            {
                // Get all projects of this user, including selected project if it's existing
                List<ProjectModel> allProjectsOfThisUser = (new GetProjects()).ExecuteToList();
                etrTaskViewModel.ProjectModels = allProjectsOfThisUser;

                ViewBag.IsAdminRole = true;
            }
            else
            {
                etrTaskViewModel.ProjectModels = null;
                ViewBag.IsAdminRole = false;
            }

            #endregion

            #region Check user role for other engineer dropdownlist

            if (Roles.IsUserInRole(ETLCredential.UserId, Constants.RoleName.Admin))
            {
                etrTaskViewModel.ProjectUserModels = (new GetActiveUsers()).Execute();
                ViewBag.IsAdminRole = true;
            }

            #endregion

            return View(etrTaskViewModel);
        }

        public ActionResult LoadTaskToEdit(string taskId)
        {
            try
            {
                decimal t = 0;
                decimal.TryParse(taskId, out t);

                ProjectTaskModel task = (new GetProjectTask()).Execute(t);

                return PartialView("_TaskDetailPartial", task);
            }
            catch (Exception ex)
            {
                LogService.Service.Error(ex);
                throw;
            }
        }

        public string AddNewProjectTask(string taskName, string projectId, string listUserId, string startDate, string endDate)
        {
            try
            {
                #region Get users to array
                if (string.IsNullOrEmpty(listUserId)) return string.Empty;
                string[] users = listUserId.Split(',');
                if (users.Length <= 0) return string.Empty;
                #endregion

                #region Add new task
                int result  = (new AddNewProjectTask()).Execute(taskName, projectId);
                #endregion

                #region Create scheduled resource usages rows for each user
                foreach (string user in users)
                {
                    if (!string.IsNullOrEmpty(user))
                    {
                        string cultureInfo = "en-US";
                        DateTime _startDate = Utils.ConvertToDate(startDate, cultureInfo);
                        DateTime _endDate = Utils.ConvertToDate(endDate, cultureInfo);
                        if (Utils.IsValidDateTime(startDate, cultureInfo) && Utils.IsValidDateTime(endDate, cultureInfo))
                        {
                            (new AddNewScheduledResourceUsage()).Execute(result.ToString(), user, _startDate, _endDate);
                        }
                    }
                }
                #endregion

                return result.ToString();
            }
            catch (Exception ex)
            {
                LogService.Service.Error(ex);
                throw;
            }
        }

        public string EditProjectTask(string taskId, string taskName, string projectId, string listUserId, string startDate, string endDate)
        {
            try
            {

                const string cultureInfo = "en-US";
                DateTime _startDate = Utils.ConvertToDate(startDate, cultureInfo);
                DateTime _endDate = Utils.ConvertToDate(endDate, cultureInfo);

                // Delete all existing scheduled resource usages
                (new DeleteScheduledResourceUsages()).Execute(taskId);

                // Get current task
                var currentTask = (new GetProjectTask()).Execute(Utils.StringToDecimal(taskId));

                // Update current task
                currentTask.TaskName = taskName;

                var result = (new UpdateProjectTask()).Execute(currentTask);

                #region Get users to array)
                if (string.IsNullOrEmpty(listUserId)) return string.Empty;
                string[] users = listUserId.Split(',');
                if (users.Length <= 0) return string.Empty;
                #endregion

                #region Create scheduled resource usages rows for each user
                foreach (string user in users)
                {
                    if (!string.IsNullOrEmpty(user))
                    {
                        (new AddNewScheduledResourceUsage()).Execute(currentTask.GenTaskId.ToString(), user, _startDate, _endDate);
                    }
                }
                #endregion

                return result.ToString();
            }
            catch (Exception ex)
            {
                LogService.Service.Error(ex);
                throw;
            }
        }


        public string DeleteProjectTask(string taskId)
        {
            try
            {

                // Delete all existing scheduled resource usages
                (new DeleteScheduledResourceUsages()).Execute(taskId);

                // Delete all existing actual resource usages
                (new DeleteActualResourceUsages()).Execute(taskId);

                // Delete task
                var result = (new DeleteProjectTask()).Execute(taskId);
                
                return result.ToString();
            }
            catch (Exception ex)
            {
                LogService.Service.Error(ex);
                throw;
            }
        }
        public string SetProjectLeadEngineer(string projectId, string userId)
        {
            try
            {
                int result = (new UpdateProjectLeadEngineer()).Execute(projectId, userId);

                return result.ToString();
            }
            catch (Exception ex)
            {
                LogService.Service.Error(ex);
                throw;
            }
        }

        #region Get tasks, project detailed by project

        /// <summary>
        /// Return a partial view of task grid
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        public ActionResult GetTask(decimal projectId)
        {
            // check authenticated status
            if (!WebSecurity.IsAuthenticated) return null;


            if (projectId > 0)
            {
                IEnumerable<ProjectTaskModel> taskList = (new GetProjectTasks()).Execute(projectId);
                return PartialView("_TaskGridPartial", taskList);
            }
            else
            {
                return null;
            }
        }

        #endregion
    }
}